package virtorina.client.admin;

import java.util.LinkedHashSet;
import java.util.LinkedList;

import virtorina.client.admin.dto.LabelDTO;
import virtorina.client.room.dto.InfoDTO;
import virtorina.client.room.rpc.GWTInsertQuestions;
import virtorina.client.room.rpc.GWTInsertQuestions.Util;
import virtorina.client.room.rpc.GWTInsertQuestionsAsync;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimpleRadioButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;

public class QInsert implements EntryPoint {
	private SimpleRadioButton type0 = SimpleRadioButton.wrap(DOM
			.getElementById("type0"));
	private SimpleRadioButton type1 = SimpleRadioButton.wrap(DOM
			.getElementById("type1"));
	private SimpleRadioButton type2 = SimpleRadioButton.wrap(DOM
			.getElementById("type2"));
	private SimpleRadioButton type3 = SimpleRadioButton.wrap(DOM
			.getElementById("type3"));
	private TextArea tb = TextArea.wrap(DOM.getElementById("QITB"));
	private Button button = Button.wrap(DOM.getElementById("QIButton"));
	private TextArea ans = TextArea.wrap(DOM.getElementById("QIAns"));
	private TextArea labels = TextArea.wrap(DOM.getElementById("QILabels"));
	private TextBox copyright = TextBox.wrap(DOM.getElementById("QICopyRight"));
	private TextBox author = TextBox.wrap(DOM.getElementById("QIAuthor"));
	private TextBox time = TextBox.wrap(DOM.getElementById("QITime"));
	private TextBox pic = TextBox.wrap(DOM.getElementById("QIUpload"));
	private TextBox idToLoad = TextBox.wrap(DOM.getElementById("QIID"));
	private Button loadBtn = Button.wrap(DOM.getElementById("QILoad"));
	private HTML GeoMessage = new HTML();
	private FileUpload audio = new FileUpload();
	private LinkedList<LabelDTO> labelsList;

	class MyLabel extends HTML {
		MyLabel(String code) {
			super(code);
			super.addClickHandler(new ClickHandler() {

				@Override
				public void onClick(ClickEvent event) {
					labels.setText(labels.getText() + getHTML() + "\n");

				}
			});
		}
	}

	void coninueConstruct() {
		type0.setValue(true);
		type2.setEnabled(false);
		pic.setVisible(false);
		GeoMessage.setStyleName("alert alert-info");
		GeoMessage
				.setHTML("Enter coords with comma, \"59.8,29.7\" for example (w/ out \")<br> <b>Карта пока только общемировая - не надо спрашивать объекты внутри городов!</b>");
		RootPanel.get("QIGeoMes").add(GeoMessage);
		GeoMessage.setVisible(false);
		time.setText("20");

		HTML text = new HTML("Subjects:");
		RootPanel.get("QILabelsList").add(new Label("loading..."));
		getAllLabels();
		text.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				RootPanel.get("QILabelsList").clear();
				RootPanel.get("QILabelsList").add(new Label("loading..."));
				getAllLabels();

			}
		});
		loadBtn.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (idToLoad.getText().length() < 2) {
					return;
				}
				System.out.println("t");
				Long id = new Long(idToLoad.getText());
				Util.getInstance().getQuestionByID(id,
						new AsyncCallback<InfoDTO>() {

							@Override
							public void onSuccess(InfoDTO r) {
								if (r == null) {
									setMessage("Such question doesn't exist");
									return;
								}
								String quest = r.getQuestion();
								ans.setText("");
								pic.setText("");
								for (String s : r.getAnswers()) {
									ans.setText(ans.getText() + s + "\n");
								}
								labels.setText("");
								for (String s : r.getLabels()) {
									labels.setText(labels.getText() + s + "\n");
								}
								copyright.setText(r.getProvider());
								author.setText(r.getAuthor());
								time.setText((r.getDuration() / 1000) + "");
								switch (r.getType()) {
								case 0:
									type0.setValue(true);
									tb.setText(quest);
									pic.setVisible(false);
									break;
								case 1:
									type1.setValue(true);
									String q = quest.substring(0,
											quest.indexOf("@$PE"));
									String p = quest.substring(
											quest.indexOf("@$PE") + 4,
											quest.length());
									tb.setText(q);
									pic.setText(p);
									pic.setVisible(true);
									break;
								case 2:
									type2.setValue(true);
									break;
								case 3:
									type3.setValue(true);
									break;
								default:
									break;
								}

							}

							@Override
							public void onFailure(Throwable caught) {

							}
						});

			}
		});
		RootPanel.get("QIShowLabels").add(text);

		type0.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (type0.getValue()) {
					pic.setVisible(false);
					GeoMessage.setVisible(false);
				}
			}
		});

		type1.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (type1.getValue()) {
					pic.setVisible(true);
					GeoMessage.setVisible(false);
				}
			}
		});

		type2.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (type2.getValue()) {
					RootPanel.get("QIUpload").clear();
					audio.setName("UploadAudio");
					RootPanel.get("QIUpload").add(audio); // doesn't work
				}
			}
		});

		type3.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (type3.getValue()) {
					RootPanel.get("QIUpload").clear();
					pic.setVisible(false);
					GeoMessage.setVisible(true);
				}
			}
		});

		button.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				LinkedList<String> answrs = new LinkedList<String>();
				LinkedHashSet<String> lbls = new LinkedHashSet<String>();
				for (String a : ans.getText().split("\n")) {
					answrs.add(a);
				}
				for (String a : labels.getText().split("\n")) {
					if (a.length() > 2) {
						lbls.add(a);
					}
				}
				if (tb.getText().length() < 10) {
					setMessage("The question is too short");
					return;
				}
				if (answrs.isEmpty() || answrs.getFirst().length() < 1) {
					setMessage("Provide at least one answer");
					return;
				}
				if (lbls.isEmpty()) {
					setMessage("Add subjects - \"Common\"");
					return;
				}
				Integer tm = new Integer(time.getText());
				if (tm < 10 || tm > 40) {
					setMessage("The time limit must be between 10 & 40 seconds");
					return;
				}
				if (copyright.getText().length() < 3) {
					setMessage("Please add the sources");
					return;
				}
				int type = 0;
				if (type0.getValue()) {
					type = 0;
				} else if (type1.getValue()) {
					type = 1;
				} else if (type2.getValue()) {
					type = 2;
				} else if (type3.getValue()) {
					type = 3;
				}
				if (type == 1 && pic.getText().length() < 10) {
					setMessage("Provide the URL to the file");
					return;
				}
				String quest = "";
				switch (type) {
				case 1:
					quest = tb.getText() + "@$PE" + pic.getText();
					break;
				default:
					quest = tb.getText();
					break;
				}
				if (idToLoad.getText().length() > 1) {
					insert(new Long(idToLoad.getText()), quest, answrs, lbls,
							type, copyright.getText(), tm);
				} else {
					insert(-1L, quest, answrs, lbls, type, copyright.getText(),
							tm);
				}
				time.setText("20");
			}
		});

		String value = com.google.gwt.user.client.Window.Location
				.getParameter("id");
		try {
			int change = new Integer(value);
			idToLoad.setText(change + "");
			loadBtn.click();
			System.out.println("test");
		} catch (Exception e) {
		}
	}

	public void onModuleLoad() {
		GWTInsertQuestions.Util.getInstance().getAccessToAddQuestions(
				new AsyncCallback<String>() {
					@Override
					public void onSuccess(String res) {
						// @TODO фикс
						boolean result = true;
						if (result) {
							coninueConstruct();
							author.setText(res);
							author.setEnabled(false);
						} else {
							RootPanel.get("main").setVisible(false);
							RootPanel
									.get("block")
									.add(new HTML(
											"<h1 style=\"size: 400px;\"><a href=\"/\">This page is only available to the adminisation. Boost your IQ & join the moderator team!</a></h1>"));
						}

					}

					@Override
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
						System.out.println("fail!!!");
					}
				});

	}

	void insert(final Long id, final String question,
			LinkedList<String> answer, final LinkedHashSet<String> labels,
			final Integer type, String copy, Integer time) {
		((GWTInsertQuestionsAsync) GWT.create(GWTInsertQuestions.class))
				.insertQuestions(id, question, answer, labels, type, copy,
						time, new AsyncCallback<Long>() {

							@Override
							public void onFailure(Throwable caught) {
								setMessage("error", "Server connection error");

							}

							@Override
							public void onSuccess(Long result) {
								if (result > 0) {
									tb.setText("");
									ans.setText("");
									pic.setText("");
									QInsert.this.labels.setText("");
									String t = question;
									if (type == 1) {
										t = t.substring(0, t.indexOf("@$PE"));
									}
									if (t.length() > 20) {
										t = t.substring(0, 20) + "...";
									}
									String act = "added";
									if (id > 0) {
										act = "updated";
									}
									setMessage("success", "Question \"" + t
											+ "\" " + act + " (id " + result
											+ ")");
									if (!labelsList.containsAll(labels)) {
										getAllLabels();
									}
								} else if (result.equals(-1L)) {
									setMessage("error",
											"Such ID doesn't exist!");
								} else {
									setMessage("error", "Something is wrong");
								}

							}

						});
	}

	void getAllLabels() {
		((GWTInsertQuestionsAsync) GWT.create(GWTInsertQuestions.class))
				.getAllLabels(new AsyncCallback<LinkedList<LabelDTO>>() {

					@Override
					public void onSuccess(LinkedList<LabelDTO> result) {
						labelsList = new LinkedList<LabelDTO>(result);
						HTML h;
						RootPanel.get("QILabelsList").clear();
						for (LabelDTO ld : labelsList) {
							h = new MyLabel(ld.getName());
							RootPanel.get("QILabelsList").add(h);
						}

					}

					@Override
					public void onFailure(Throwable caught) {
						System.out.println("error");

					}
				});
	}

	void setMessage(String message) {
		setMessage("warning", message);
	}

	void setMessage(String type, String message) {
		if (type.equals("warning")) {
			type = "";
		} else {
			type = "alert-" + type;
		}
		RootPanel.get("QIMessage").clear();
		RootPanel.get("QIMessage").add(
				new HTML("<div class=\"alert " + type
						+ "\"><a class=\"close\" data-dismiss=\"alert\">×</a>"
						+ message + "</div>"));
	}
}